Ext.ns('App', 'App.control');

// create the Data Store
store = new Ext.data.JsonStore({
    root: 'results',
    //        totalProperty: 'totalCount',
    idProperty: 'projectid',
    remoteSort: true,
    
    fields: ['reviewstatus', {
        name: 'roadway',
        type: 'boolean'
    }, {
        name: 'description',
        type: 'string'
    }, {
        name: 'end_date',
        type: 'date',
        dateFormat: 'm/d/Y'
    }, {
        name: 'projectno',
        type: 'string'
    }, {
        name: 'projectid',
        type: 'string'
    }, {
        name: 'project',
        type: 'string'
    }, {
        name: 'garage',
        type: 'boolean'
    }, {
        name: 'adaparking',
        type: 'boolean'
    }, {
        name: 'sidewalk',
        type: 'boolean'
    }, {
        name: 'start_date',
        type: 'date',
        dateFormat: 'm/d/Y'
    }, {
        name: 'pm',
        type: 'string'
    }, {
        name: 'geometry',
        type: 'string'
    }, {
        name: 'x',
        type: 'float'
    }, {
        name: 'y',
        type: 'float'
    }, ],
    
    // load using script tags for cross domain, if the data in on the same domain as
    // this page, an HttpProxy would be better
    proxy: new Ext.data.HttpProxy({
        url: '/test'
    })
});
store.setDefaultSort('start_date', 'desc');

App.control.gridPanel = Ext.extend(Ext.grid.GridPanel, {

    onButtonClick: function(btn, e){
        if (btn.text == 'Delete') {
            this.onDelete()
            return
        }
        if (btn.text == 'New') {
            if (app_edit_form) {
                app_edit_form.new_entry()
                
                
            }
            else {
                app_edit_form = new App.control.editForm()
            }
            
            return
        }
        
        if (btn.text == 'Edit') {
            this.onDelete()
            return
        }
        
        
        
        
        editform = new EditForm({
            title: 'New Impact...',
            buttons: [{
                text: 'Save',
                handler: function(formpanel, action){
                    editform.getForm().submit({
                        clientValidation: true,
                        url: '/test',
                        method: 'post',
                        params: {
                            request_type: 'new'
                        },
                        
                        success: function(form, action){
                            Ext.Msg.alert('Success', action.result.msg);
                            
                            store.load();
                        },
                        failure: function(form, action){
                            if (action.failureType == 'client') {
                                Ext.Msg.alert('Invalid Entry', 'Please fix the errors on your form and try again.')
                            }
                            else {
                                Ext.Msg.alert('Server error', action.result.msg)
                            }
                            
                        }
                    });
                }
            }, {
                text: 'Cancel',
                handler: function(form, action){
                    form.findParentByType('window').destroy();
                }
            }]
        });
        
        var container = Ext.getCmp('map-control');
        editform.render(container.body);
        
        //                        win = new Ext.Window({
        //                            title: 'New Impact ....',
        //                            width: 800,
        //                            height: 600,
        //                            autoScroll: true,
        //                            layout: 'fit',
        //                            items: [editform],
        //                            modal: true
        //                        });
        //                        
        //                        win.show();
    
    
    },
    
    onDelete: function(btn, e){
    
        var sel = this.getSelectionModel().getSelected();
        if (sel) {
            Ext.Ajax.request({
                url: '/test',
                params: {
                    projectid: sel.get('projectid'),
                    request_type: 'delete'
                },
                method: 'post',
                success: function(result, request){
                    var jsondata = Ext.util.JSON.decode(result.responseText);
                    if (jsondata.success) {
                        store.load()
                        
                    }
                    else {
                        Ext.Msg.alert('Failed to delete the record')
                    }
                }
            })
        }
        else {
            Ext.Msg.alert('No record is selected')
            
        }
        
    },
    onNew: function(){
    
        editform = new EditForm({
            title: 'New Impact...',
            buttons: [{
                text: 'Save',
                handler: function(formpanel, action){
                    editform.getForm().submit({
                        clientValidation: true,
                        url: '/test',
                        method: 'post',
                        params: {
                            request_type: 'new'
                        },
                        
                        success: function(form, action){
                            Ext.Msg.alert('Success', action.result.msg);
                            
                            store.load();
                        },
                        failure: function(form, action){
                            if (action.failureType == 'client') {
                                Ext.Msg.alert('Invalid Entry', 'Please fix the errors on your form and try again.')
                            }
                            else {
                                Ext.Msg.alert('Server error', action.result.msg)
                            }
                            
                        }
                    });
                }
            }, {
                text: 'Cancel',
                handler: function(form, action){
                    form.findParentByType('window').destroy();
                }
            }]
        });
        
        var container = Ext.getCmp('map-control');
        editform.render(container.body);
        
        //                        win = new Ext.Window({
        //                            title: 'New Impact ....',
        //                            width: 800,
        //                            height: 600,
        //                            autoScroll: true,
        //                            layout: 'fit',
        //                            items: [editform],
        //                            modal: true
        //                        });
        //                        
        //                        win.show();
    
    
    },
    onToggle: function(btn, pressed){
        var view = this.getView();
        view.showPreview = pressed;
        view.refresh();
    },
    onEdit: function(){
    
        var sel = this.getSelectionModel().getSelected();
        if (sel) {
            editform = new EditForm({
                buttons: [{
                    text: 'Save',
                    handler: function(formpanel, action){
                        editform.getForm().submit({
                            clientValidation: true,
                            url: '/test',
                            method: 'post',
                            params: {
                                request_type: 'update'
                            },
                            
                            success: function(form, action){
                                Ext.Msg.alert('Success', action.result.msg);
                                formpanel.findParentByType('window').destroy();
                                store.load();
                            },
                            failure: function(form, action){
                                if (action.failureType == 'client') {
                                    Ext.Msg.alert('Invalid Entry', 'Please fix the errors on your form and try again.')
                                }
                                else {
                                    Ext.Msg.alert('Server error', action.result.msg)
                                }
                                
                            }
                        });
                    }
                }, {
                    text: 'Cancel',
                    handler: function(form, action){
                        form.findParentByType('window').destroy();
                    }
                }]
            });
            
            var win = new Ext.Window({
                title: 'Editing ....',
                width: 800,
                height: 600,
                autoScroll: true,
                layout: 'fit',
                items: [editform],
                modal: true
            });
            win.show();
            editform.getForm().loadRecord(sel)
        }
        else {
            Ext.Msg.alert('No record is selected')
            
        }
        
        
    },
    
    initComponent: function(){
        function highlight(val){
            if (val) {
                return '<span style="color:red;">Yes</span>';
            }
            else {
                return '<span style="color:green;">No</span>';
            }
        };
        var config = {
        
            width: 500,
            height: 500,
            iconCls: 'icon-impact',
            
            store: store,
            trackMouseOver: true,
            disableSelection: false,
            loadMask: true,
            
            // grid columns
            columns: [{
                header: "Project No.",
                dataIndex: 'projectno',
                width: 50,
                sortable: true
            }, {
                header: "ID",
                dataIndex: 'projectid',
                width: 50,
                sortable: true,
                hidden: true
            }, {
                header: "Project",
                dataIndex: 'project',
                width: 100,
                sortable: true
            }, {
                header: "PM",
                dataIndex: 'pm',
                width: 50,
                sortable: true
            }, {
                header: "Start",
                dataIndex: 'start_date',
                width: 30,
                renderer: Ext.util.Format.dateRenderer('m/d/Y'),
                sortable: true,
                hidden: false
            }, {
                header: "End",
                dataIndex: 'end_date',
                width: 50,
                renderer: Ext.util.Format.dateRenderer('m/d/Y'),
                sortable: true,
                hidden: false
            }, {
                header: "Roadway",
                dataIndex: 'roadway',
                width: 30,
                renderer: highlight,
                sortable: true,
                hidden: false
            }, {
                header: "Garage",
                dataIndex: 'garage',
                renderer: highlight,
                width: 30,
                sortable: true,
                hidden: false
            }, {
                header: "ADA Parking",
                dataIndex: 'adaparking',
                renderer: highlight,
                width: 30,
                sortable: true,
                hidden: false
            }, {
                header: "Sidewalk",
                dataIndex: 'sidewalk',
                renderer: highlight,
                width: 30,
                sortable: true,
                hidden: false
            }, {
                header: "geometry",
                dataIndex: 'geometry',
                width: 30,
                sortable: true,
                hidden: true
            }, {
                header: "y",
                dataIndex: 'y',
                width: 30,
                hidden: true
            }, {
                header: "x",
                dataIndex: 'x',
                width: 30,
                sortable: true,
                hidden: true
            }],
            sm: new Ext.grid.RowSelectionModel({
                singleSelect: true,
                listeners: {
                    rowselect: function(sm, row, rec){
                        //editform.getForm().loadRecord(rec)
                        // mapPanel.setTitle('Map Panel - ' + rec.data.project)
                    }
                }
            }),
            
            // customize view config
            viewConfig: {
                forceFit: true,
                enableRowBody: true,
                showPreview: true,
                getRowClass: function(record, rowIndex, p, store){
                    function getURL(record){
                        
                        var url;
                        var path = [];
						pt = [record.data.x, record.data.y];
                        
                        var x = Ext.util.JSON.decode(record.data.geometry);//geojson format, //x = 
                        for (var i = 0; i < x.coordinates[0].length; i++) {
                            var xy = x.coordinates[0][i];
                            path.push([xy[1] + ',' + xy[0]])
                        }
                        
                        var path_str = path.join('|');
                        
                        
                        
                        url = 'http://maps.google.com/maps/api/staticmap?size=300x200&path=fillcolor:0xAA000033|color:0xFFFFFF00|' + path_str + '&sensor=false&markers=color:blue|' + pt[1] + ',' + pt[0];
                        
                        
                        
                        return url
                    };
                    if (this.showPreview) {
                    
                        
                        
                        var html = String.format('<div style="float:left;padding:5 5 5 5;" ><img src="{4}"/></div><div >{0} -- {1}<br>Traffic Impacts:{2}<br>{3}</div>', Ext.util.Format.dateRenderer('m/d/y')(record.data.start_date), Ext.util.Format.dateRenderer('m/d/y')(record.data.end_date), '', record.data.description, getURL(record));
                        p.body = '<p style="color:grey;">' + html + '</p>';
                        return 'x-grid3-row-expanded';
                    }
                    return 'x-grid3-row-collapsed';
                }
            },
            listeners: {
                //viewready:
                viewready: function(g){
                
                    g.getSelectionModel().selectRow(0);
                }
            },
            
            // paging bar on the bottom
            tbar: new Ext.Toolbar({
                items: [{
                    xtype: 'button',
                    text: 'Delete',
                    iconCls: 'icon-delete',
                    handler: this.onButtonClick,
                    scope: this
                
                }, {
                    xtype: 'button',
                    text: 'Edit',
                    id: 'app-grid-panel-edit-btn',
                    iconCls: 'icon-edit'
                    //                    handler: this.onButtonClick,
                    //                    scope: this
                
                }, {
                    xtype: 'button',
                    text: 'New',
                    iconCls: 'icon-add',
                    handler: this.onButtonClick,
                    scope: this
                
                }, {
                    xtype: 'button',
                    pressed: true,
                    enableToggle: true,
                    text: 'Show Preview',
                    //                cls: 'x-btn-text-icon details',
                    toggleHandler: this.onToggle,
                    scope: this
                }]
            })
        }; // eo config object
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        
        App.control.gridPanel.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
    //    ,onRender: function(){
    //        this.store.load();
    //        
    //        App.control.mapField.superclass.onRender.apply(this, arguments);
    //    } // eo function onRender
});

Ext.reg('app_gridpanel', App.control.gridPanel);


